package org.yunai.swjg.server.module.currency;

import org.springframework.stereotype.Service;
import org.yunai.swjg.server.core.constants.SysMessageConstants;
import org.yunai.swjg.server.core.service.Online;
import org.yunai.swjg.server.module.player.vo.Player;
import org.yunai.swjg.server.rpc.message.S_C.S_C_PlayerAddCurrencyResp;
import org.yunai.swjg.server.rpc.message.S_C.S_C_SysMessageReq;

/**
 * 货币逻辑Service
 * User: yunai
 * Date: 13-5-12
 * Time: 上午1:16
 */
@Service
public class CurrencyService {

    /**
     * 验证玩家是否能够添加指定货币指定钱数<br />
     * 当添加钱小于等于0，认为验证通过<br />
     *
     * @param online 在线信息
     * @param currency 货币枚举
     * @param incrNum 增加货币数
     * @param showError 是否发送错误消息给客户端
     * @return 是否能够添加钱
     */
    public boolean canAdd(Online online, Currency currency, Integer incrNum, boolean showError) {
        if (incrNum <= 0) {
            return true;
        }
        Player player = online.getPlayer();
        if (incrNum > currency.getMax() ||
                player.getCurrency(currency) >= currency.getMax() - incrNum) {
            if (showError) {
                online.write(new S_C_SysMessageReq(SysMessageConstants.PLAYER_CURRENCY_OVER_MAX));
            }
            return false;
        }
        return true;
    }

    /**
     * 添加钱，并提示客户端增加的钱数<br />
     * 该方法不进行是否添加钱的验证，所以，调用该方法前，请调用{@link #canAdd(org.yunai.swjg.server.core.service.Online, Currency, Integer, boolean)}
     *
     * @param online 在线信息
     * @param currency 货币枚举
     * @param incrNum 增加货币数
     */
    public void add(Online online, Currency currency, Integer incrNum) {
        if (incrNum <= 0) {
            return;
        }
        // 修改数据
        Player player = online.getPlayer();
        Integer newCount = player.getCurrency(currency) + incrNum;
        player.changeCurrency(currency, newCount);
        // 提示客户端
        online.write(new S_C_PlayerAddCurrencyResp(currency.getValue(), incrNum));
        // TODO 日志
    }
}
